/*
 * @Descripttion: 
 * @Author: 21070032
 * @Date: 2021-04-29 13:46:00
 * @LastEditors: 21070032
 * @LastEditTime: 2021-09-06 00:25:55
 */
const Router = require('koa-router');
const router = new Router();
const axios = require('axios');
const config = require('../config');
const { getToken, setToken } = require('../libs/common');

router.post('/login', async (ctx) => {
    const user = config.users.find(item => item.username == ctx.request.body.username);
    if (!user) {
        throw {
            status: 400,
            body: { msg: '账户不存在' }
        };
    } else if (ctx.request.body.password !== user.password) {
        throw {
            status: 400,
            body: { msg: '账户或密码不正确' }
        };
    }
    // console.log('[fs.session.access_token]', getToken(), !getToken())
    if (!getToken()) {
        const { appid, secret, grant_type } = require('../config')
        const res = await axios({
            method: 'get',
            url: '/cgi-bin/token',
            params: {
                appid,
                secret,
                grant_type
            }
        });
        console.log('[res.data.access_token]1', res)
        console.log('[res.data.access_token]2', res.data)
        const json = {
            access_token: res.data.access_token,
            expires_in: new Date().getTime() + res.data.expires_in*1000
        }
        setToken(JSON.stringify(json));
        ctx.body = {
            code: 200,
            data: res.data.access_token,
            msg: 'ok'
        };
    }
    ctx.body = {
        code: 200,
        data: {
            access_token: JSON.parse(getToken()).access_token
        },
        msg: 'ok'
    };
})
router.use('/store', require('./store'))
router.use('/banner', require('./banner'))
router.use('/user', require('./user'))
router.use('/works', require('./works'))
router.use('/work', require('./work'))
router.use('/worksType', require('./worksType'))
router.use('/workType', require('./workType'))
router.use('/server', require('./server'))
router.use('/serverCategory', require('./serverCategory'))
router.use('/type', require('./type'))
router.use('/quotation', require('./quotation'))
router.use('/quotationCategory', require('./quotationCategory'))

module.exports = router.routes();